<?php
class Categories extends CI_Controller{
	public function add(){
		$this->load->helper(array('form', 'url'));
	
		$this->load->library('form_validation');
	
		$this->form_validation->set_rules('categorie', 'Categorie');
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('v_categorie_add');
		}
		else
		{
			$this->submit_add($_POST["categorie"]);
		}
	}
	
	public function submit_add($name){
		$cat = new Categorie();
		$cat->setNom($name);
		$this->doctrine->em->persist($cat);
		$this->doctrine->em->flush();
	}
 
    public function all(){
        $query = $this->doctrine->em->createQuery("SELECT c FROM categorie c");
        $categories = $query->getResult();
        $this->load->view('v_categorie',array('categories'=>$categories));
    }
    
    public function update(){
    	$this->load->helper(array('form', 'url'));
	
		$this->load->library('form_validation');
	
		$this->form_validation->set_rules('catname', 'Catname', 'trim|required|min_lenght[2]|maxlenght[12]|xss_clean');
		if ($this->form_validation->run() == FALSE)
		{
			$this->load->view('v_categorie_modif');
		}
		else
		{
			$this->submit_update($_POST["catname"], $_POST["newcatname"]);
		}
    }
    
    public function submit_update($name, $newName){
        $cat=$this->doctrine->em->getRepository("Categorie")->findOneBy(array("nom"=>$name));
        $cat->setNom($newName);
		$this->doctrine->em->flush();
    }
    
    public function delete(){
    	$this->load->helper(array('form', 'url'));
    
    	$this->load->library('form_validation');
    
    	$this->form_validation->set_rules('catname', 'Catname', 'trim|required|min_lenght[2]|maxlenght[12]|xss_clean');
    	if ($this->form_validation->run() == FALSE)
    	{
    		$this->load->view('v_categorie_delete');
    	}
    	else
    	{
    		$this->submit_delete($_POST["catname"]);
    	}
    }
    
    public function submit_delete($name){
    	$cat=$this->doctrine->em->getRepository("Categorie")->findOneBy(array("nom"=>$name));
    	$this->doctrine->em->remove($cat);
    	$this->doctrine->em->flush();
    }
}
?>